import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/associating_rooms/widgets/select_rooms/index.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

enum LockType {
  room,
  public
}
class AssociatingRooms extends StatefulWidget {
  final LockType type;
  final int lockDeviceId;
  const AssociatingRooms({super.key, required this.type, required this.lockDeviceId});

  @override
  State<StatefulWidget> createState() => _AssociatingRoomsState();

}

class _AssociatingRoomsState extends State<AssociatingRooms> {

  List _list = [];
  bool _isManageMode = false;
  Set<int> _selectedRoomIds = {};
  bool _isLoading = false;
  
  bool _public() {
    return widget.type == LockType.public;
  }

  Future<void> _getRooms() async {
    if (_isLoading) return;
    
    setState(() {
      _isLoading = true;
    });
    
    try {
      Map resData;
      if (_public()) {
        resData = await entranceGuardApi.boundRooms(widget.lockDeviceId);
      } else {
        resData = await apartmentApi.getRoomList({});
      }
      
      setState(() {
        _list = resData["data"] ?? [];
        _isLoading = false;
      });
    } catch (error) {
      setState(() {
        _isLoading = false;
      });
      print(error);
    }
  }

  void _associatedRooms(int roomId) async {
    Map<String, dynamic> params = {
      "lockId": widget.lockDeviceId,
      "roomId": roomId,
    };
    print("params:>>> $params");
    await lockApi.bindRoom(params);
    EasyLoading.showToast("关联成功");
    if (context.mounted) {
      Navigator.pop(context);
    }
  }
  
  void _toggleManageMode() {
    setState(() {
      _isManageMode = !_isManageMode;
      if (!_isManageMode) {
        _selectedRoomIds.clear();
      }
    });
  }
  
  void _toggleRoomSelection(int roomId) {
    setState(() {
      if (_selectedRoomIds.contains(roomId)) {
        _selectedRoomIds.remove(roomId);
      } else {
        _selectedRoomIds.add(roomId);
      }
    });
  }
  
  Future<void> _unbindSelectedRooms() async {
    if (_selectedRoomIds.isEmpty) {
      EasyLoading.showToast("请选择要解除关联的房间");
      return;
    }
    
    try {
      await entranceGuardApi.unbindRooms(widget.lockDeviceId, _selectedRoomIds.map((item) => item.toString()).join(","),);
      
      EasyLoading.showToast("解除关联成功");
      setState(() {
        _isManageMode = false;
        _selectedRoomIds.clear();
      });
      
      _getRooms();
    } catch (error) {
      print(error);
      EasyLoading.showToast("解除关联失败");
    }
  }

  @override
  void initState() {
    _getRooms();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "关联的房间",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      showSearch: false,
      showFloatBtn: _public() && !_isManageMode,
      floatOnPress: () {
        Navigator.push(
          context, CupertinoPageRoute(
            builder: (BuildContext context) {
              return SelectRooms(lockDeviceId: widget.lockDeviceId);
            },
          ),
        ).then((result) {
          if (result == true) {
            _getRooms();
          }
        });
      },
      floatChildren: _public() ? const [
        SizedBox(height: 80,),
      ] : null,
      children: [
        Container(
          padding: EdgeInsets.only(top: _public() ? 60 : 0, bottom: 78),
          child: RefreshIndicator(
            onRefresh: _getRooms,
            child: ListView.separated(
              itemBuilder: (context, index) {
                final room = _list[index];
                final roomId = room["roomId"];
                final isSelected = _selectedRoomIds.contains(roomId);
                
                return Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                  height: 48,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      if (_isManageMode) {
                        _toggleRoomSelection(roomId);
                      }
                    },
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("${room["buildingName"]}${room["name"]}",),
                        _isManageMode 
                          ? Icon(
                              isSelected ? Icons.check_circle : Icons.circle_outlined, 
                              color: ThemeVars.colorPrimary,
                            )
                          : SizedBox()
                      ],
                    ),
                  ),
                );
              },
              separatorBuilder: (context, index) => const SolidDivider(padding: EdgeInsets.only(left: 12)),
              itemCount: _list.length
            ),
          ),
        ),
        if (_public()) Positioned(
          width: MediaQuery.of(context).size.width,
          top: 0,
          left: 0,
          child: Container(
            width: MediaQuery.of(context).size.width,
            decoration: const BoxDecoration(
              color: ThemeVars.colorBackground,
            ),
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                  decoration: const BoxDecoration(
                      color: Colors.white
                  ),
                  child: const SizedBox(
                    height: 40,
                    child: TextField(
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                            borderSide: BorderSide.none
                        ),
                        hintText: "请输入",
                        isDense: true,
                        filled: true,
                        fillColor: ThemeVars.colorBackground,
                        suffixIcon: SizedBox(
                          child: Icon(Icons.search, size: 20,),
                        ),
                      ),
                      style: TextStyle(fontSize: 14),
                    ),
                  ),
                ),
                const SizedBox(height: 10, child: DecoratedBox(decoration: BoxDecoration(color: ThemeVars.colorBackground)),)
              ],
            )
          )
        ),
        Positioned(
          bottom: 0,
          left: 0,
          width: MediaQuery.of(context).size.width,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
            decoration: const BoxDecoration(
              color: Colors.white,
              boxShadow: [ThemeVars.boxShadow]
            ),
            child: _isManageMode 
              ? Row(
                  children: [
                    Expanded(
                      child: Button(
                        type: ButtonType.primaryOutline,
                        onPressed: _toggleManageMode,
                        child: const Text("退出")
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Button(
                        type: ButtonType.primary,
                        onPressed: _unbindSelectedRooms,
                        child: const Text("解除关联")
                      ),
                    ),
                  ],
                )
              : Button(
                  type: ButtonType.primary,
                  onPressed: _public() ? _toggleManageMode : () {},
                  child: Text(_public() ? "管理" : "解除关联")
                ),
          )
        ),
      ],
    );
  }
}